﻿using log4net;
using SQLDataUploadHelper.models.domain;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace SQLDataUploadHelper.daos.bases
{
    public class DatabaseBaseDao
    {
        private readonly ILog log = LogManager.GetLogger(App.LogRepository.Name, typeof(DatabaseBaseDao));

        protected SqlConnection sqlConnection;

        /// <summary>
        /// 最后一次的错误信息
        /// </summary>
        public string? LastErrorMessage { get; set; }

        /// <summary>
        /// 连接信息
        /// </summary>
        public SqlConnectConfig? SqlConnectInfo { get; set; }


        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="ip">数据库ID</param>
        /// <param name="port">数据库端口</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">用户密码</param>
        public bool open()
        {
            //string connectionString = "server=127.0.0.1;port=3306;user id=root;password=971212";
            if (SqlConnectInfo == null)
            {
                log.Warn("连接信息为空");
                LastErrorMessage = "连接信息为空";
                return false;
            }
            if (sqlConnection != null &&
                sqlConnection.State != ConnectionState.Closed)
            {
                LastErrorMessage = "";
                return true;
            }

            sqlConnection = new SqlConnection(SqlConnectInfo.getConnectCommond());
            try
            {
                sqlConnection.Open();
                return sqlConnection.State == ConnectionState.Open;
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.ToString());
                log.Error("连接出现异常=" + ex.ToString());
                LastErrorMessage = "连接异常:" + ex.Message;
            }
            return false;
        }

        /// <summary>
        /// 断开数据连接
        /// </summary>
        public void close()
        {
            if (sqlConnection != null)
            {
                sqlConnection.Close();
            }
        }

        /// <summary>
        /// 获取所有表信息
        /// </summary>
        /// <param name="database">数据库</param>
        public List<string> GetTables()
        {
            List<string> tables = new List<string>();
            if (!open())
            {
                log.Error("数据库打开失败");
                return tables;
            }
            DataTable dt = sqlConnection.GetSchema("Tables");
            foreach (DataRow row in dt.Rows)
            {
                string tablename = (string)row[2];
                tables.Add(tablename);
            }
            return tables;
        }

        ~DatabaseBaseDao()
        {
            close();
        }

    }
}
